<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>-->
    <script src="jq.js"></script>
</head>
<body>
<audio controls></audio>
<button>start</button>
<script>

    //访问用户媒体设备的兼容方法
    function getUserMedia(constrains, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新标准API
            navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit内核浏览器
            navigator.webkitGetUserMedia(constrains).then(success).catch(error);
        } else if (navigator.mozGetUserMedia) {
            //Firefox浏览器
            navagator.mozGetUserMedia(constrains).then(success).catch(error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constrains).then(success).catch(error);
        }
    }

    var audio = $('audio');

    //成功的回调函数
    function success(stream) {
        alert(0);
        var recorder = new MediaRecorder(stream);
        alert(1);
        $('button').on('click', function () {
            alert(2);
            var txt = $(this).html();
            if (txt === 'start') {
                recorder.start();
                $(this).html('end');
            } else {
                recorder.stop();
                $(this).html('start');
            }
        });
        recorder.ondataavailable = function (event) {
            alert(3);
            var data = event.data;
            //兼容webkit内核浏览器
            var CompatibleURL = window.URL || window.webkitURL;
            //将视频流设置为video元素的源
            audio.attr('src', CompatibleURL.createObjectURL(data));
        };
    }

    //异常的回调函数
    function error(error) {
        console.log("访问用户媒体设备失败：", error.name, error.message);
    }

    if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        var constraints = {
            audio: true
        };
        getUserMedia(constraints, success, error);
    } else {
        alert("你的浏览器不支持访问用户媒体设备");
    }


</script>
</body>
</html>